from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q
from app.controllers.marketing.integral import integral_controller
from app.controllers.marketing.integral_rule import integral_rule_controller
from app.core.ctx import CTX_USER_ID
from app.core.dependency import DependCustomerAuth
from app.models import CustomerUser
from fastapi.responses import JSONResponse

mini_integral_router = APIRouter()
model_name = "积分"


@mini_integral_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
):
    q = Q()
    user_id = CTX_USER_ID.get()
    if user_id:
        q &= Q(user_id=user_id)

    total, data = await integral_controller.do_list(page=page, page_size=page_size, search=q)
    price = await integral_controller.do_user_info(user_id)

    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user.name for user in users}
    type_objs = await integral_rule_controller.level_list()
    for item in data:
        item['total'] = int(price)
        item['user_name'] = users_dict.get(item['user_id'], "已删除用户")
        if item['direction'] == 1:
            item['direction_name'] = "增加"
        else:
            item['direction_name'] = "减少"
        item['type_name'] = type_objs[item['type']]

    return JSONResponse(content={"code": 200, "data": data,"total":total,"page":page,"page_size":page_size,"integral":int(price)}, status_code=200)
